package com.ding.dailyup.service;

import com.ding.dailyup.enums.YesOrNo;
import com.ding.dailyup.model.StockStrategy;
import com.ding.dailyup.model.UserCollectStrategy;
import com.ding.dailyup.repository.UserCollectStrategyRepository;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserCollectStrategyService {
	@Autowired
	private UserCollectStrategyRepository userCollectStrategyRepository;
	@Autowired
	private StockStrategyService stockStrategyService;

	public List<UserCollectStrategy> listUserCollectStrategies(Long userId) {
		return userCollectStrategyRepository
				.findAllByUserIdAndStatusOrderByIdDesc(userId,
						YesOrNo.YES.value())
				.orElse(Lists.newArrayList());
	}
	@Transactional(rollbackFor = Exception.class)
	public void collectStrategy(Long strategyId, String strategyName,
			Long userId) {
		UserCollectStrategy userCollectStrategy = new UserCollectStrategy();
		userCollectStrategy.setStrategyName(strategyName);
		userCollectStrategy.setStrategyId(strategyId);
		userCollectStrategy.setUserId(userId);
		userCollectStrategyRepository.save(userCollectStrategy);
	}
	@Transactional(rollbackFor = Exception.class)
	public void cancelCollectStrategy(Long strategyId, Long userId) {
		userCollectStrategyRepository.cancelCollect(userId,strategyId);
	}

	/**
	 * 帮用户保存默认策略
	 * 
	 * @param uid
	 *            uid
	 */
	@Transactional(rollbackFor = Exception.class)
	public void collectDefaultStrategy(Long uid) {
		List<StockStrategy> stockStrategies = stockStrategyService
				.listDefaultStrategies();
		for (StockStrategy stockStrategy : stockStrategies) {
			UserCollectStrategy userCollectStrategy = new UserCollectStrategy();
			userCollectStrategy
					.setStrategyName(stockStrategy.getStrategyName());
			userCollectStrategy.setStrategyId(stockStrategy.getId());
			userCollectStrategy.setUserId(uid);
			userCollectStrategyRepository.save(userCollectStrategy);
		}
	}
}
